import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/search_widget.dart';
import 'package:cave_flutter/widgets/whl_app_bar.dart';
import 'package:floor/floor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'package:cave_flutter/config/whl_global_config.dart';

import '../../../common/common_widget.dart';
import 'cave_home_logic.dart';

class Cave_homePage extends StatelessWidget {
  Cave_homePage({Key? key}) : super(key: key);

  final logic = Get.put(Cave_homeLogic());

  String getImageBaseUrl = WHLGlobalConfig.getInstance().getImageBaseUrl();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: WhlAppBar(
          isBack: false,
          isShowBottomLine: false,
          backgroundColor: kAppColor("#FAEDDD"),
          centerWidget: UIContainer(
            strokeWidth: 1.w,
            strokeColor: kAppBlackColor,
            radius: 19.w,
            child: SearchWidget(
              logic.editingController,
              readOnly: true,
            ),
            onTap: () {
              Get.toNamed(Routes.caveSearchPage);
            },
          ),
        ),
        body: GetBuilder<Cave_homeLogic>(builder: (logic) {
          return ListView(
            children: [
              UIContainer(
                gradientStartColor: kAppColor("#FAEDDD"),
                gradientEndColor: kAppColor("#E4E4E4"),
                gradientBegin: Alignment.topCenter,
                gradientEnd: Alignment.bottomCenter,
                bottomLeftRadius: 30.w,
                bottomRightRadius: 30.w,
                width: ScreenUtil().screenWidth,
                child: UIColumn(
                  children: [
                    UIRow(
                      children: [
                        UIImage(
                          width: 165.w,
                          height: 148.w,
                          assetImage: "cave_home_top_left.png",
                        ),
                        Expanded(
                          child: UIColumn(
                            children: [
                              UIImage(
                                  width: 190.w,
                                  height: 85.w,
                                  assetImage: "cave_home_top_right_top.png"),
                              UIImage(
                                width: 120.w,
                                height: 40.w,
                                assetImage: "cave_home_top_right_bottom.png",
                                onTap: () {
                                  Get.toNamed(Routes.createCavePage)
                                      ?.then((value) {
                                    if (value != null) {
                                      logic.getPersonalCategory();
                                    }
                                  });
                                },
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                    topGridView(),
                    UIContainer(
                      height: 72.w,
                      child: CustomScrollView(
                        physics: const ClampingScrollPhysics(),
                        scrollDirection: Axis.horizontal,
                        slivers: [
                          SliverToBoxAdapter(
                            child: UIColumn(
                              children: [
                                logic.officialCategoryOdd.isNotEmpty
                                    ? tagGridView(
                                        list: logic.officialCategoryOdd,
                                        val: logic.officialCategoryActive,
                                        margin: EdgeInsets.only(right: 39.w))
                                    : Container(),
                                logic.officialCategoryEven.isNotEmpty
                                    ? tagGridView(
                                        list: logic.officialCategoryEven,
                                        margin: EdgeInsets.only(
                                            left: 39.w, top: 5.w, bottom: 11.w))
                                    : Container(),
                              ],
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              allCaveView(),
              coveListView()
            ],
          );
        }));
  }

  Widget topGridView() {
    // if (logic.officialCaves.isEmpty) {
    //   return SizedBox();
    // }
    return UIContainer(
      margin: EdgeInsets.symmetric(vertical: 10.w),
      padding: EdgeInsets.only(left: 10.w, right: 10.w),
      height: 145.w,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 10.w,
          mainAxisExtent: 72.w,
        ),
        itemBuilder: (context, index) {
          int result = index % 3;
          double space = 7.w * result;

          return UIContainer(
            width: 72.w,
            height: 145.w,
            padding: EdgeInsets.only(top: space, bottom: 14.w - space),
            child: UIContainer(
              color: kAppBlackColor,
              radius: 17.w,
              child: Stack(
                alignment: Alignment.topCenter,
                children: [
                  UIImage(
                    margin: EdgeInsets.only(bottom: 21.w),
                    width: 72.w,
                    height: 110.w,
                    radius: 17.w,
                    disabledHttpBigImage: true,
                    // assetImage: "img_bg_home",
                    httpImage: !logic.officialCaves[index]['caveImg']
                            .toString()
                            .startsWith("http")
                        ? '${getImageBaseUrl}${logic.officialCaves[index]['caveImg']}'
                        : logic.officialCaves[index]['caveImg'],
                    fit: BoxFit.cover,
                  ),
                  Positioned(
                      left: 11.w,
                      top: 7.w,
                      right: 2.w,
                      child: UIText(
                        overflow: TextOverflow.ellipsis,
                        shrinkWrap: false,
                        textColor: kAppWhiteColor,
                        text: logic.officialCaves[index]['caveName'],
                        fontSize: 14.sp,
                      )),
                  Positioned(
                      left: 2.w,
                      bottom: 3.w,
                      right: 2.w,
                      child: Text(
                        logic.officialCaves[index]['caveName'],
                        style: TextStyle(
                          color: kAppWhiteColor,
                          overflow: TextOverflow.ellipsis,
                          fontSize: 11.sp,
                        ),
                        textAlign: TextAlign.center,
                      )),
                ],
              ),
            ),
            onTap: () {
              if (logic.officialCaves[index]['join'] == true) {
                logic.toDetailPage(logic.officialCaves[index]['id']);
              } else {
                logic.toJoinPage(logic.officialCaves[index]['id']);
              }
            },
          );
        },
        itemCount: logic.officialCaves.length,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  Widget tagGridView(
      {List<dynamic>? list, String? val, EdgeInsetsGeometry? margin}) {
    return UIContainer(
      height: 28.w,
      margin: margin,
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 10.w,
          mainAxisExtent: 78.w,
        ),
        itemBuilder: (context, index) {
          return UIText(
            width: 78.w,
            height: 28.w,
            radius: 14.w,
            color: list![index]['id'] == logic.officialCategoryActive
                ? Colors.black
                : kAppWhiteColor,
            text: list![index]['name'],
            alignment: Alignment.center,
            textColor: list![index]['id'] == logic.officialCategoryActive
                ? Colors.white
                : kAppSubTextColor,
            fontSize: 11.sp,
            onTap: () {
              logic.officialCategoryActive = list![index]['id'].toString();
              logic.update();
              logic.getOfficialCaveList(logic.officialCategoryActive);
            },
          );
        },
        itemCount: list!.length,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  Widget allCaveView() {
    return UIContainer(
      margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 13.w),
      padding: EdgeInsets.symmetric(horizontal: 13.w),
      color: kAppBlackColor,
      radius: 25.w,
      height: 100.h,
      child: Stack(
        alignment: Alignment.centerLeft,
        children: [
          for (int i = 0; i < logic.caveTop5List.length; i++)
            UIImage(
              margin: EdgeInsets.only(left: 33.w * i),
              width: 54.w,
              height: 76.h,
              radius: 18.w,
              httpImage: !logic.caveTop5List[i]['caveImg']
                      .toString()
                      .startsWith("http")
                  ? '$getImageBaseUrl${logic.caveTop5List[i]['caveImg']}'
                  : logic.caveTop5List[i]['caveImg'],
              fit: BoxFit.cover,
            ),
          UIContainer(
            margin: EdgeInsets.only(left: 33.w * 4),
            clipBehavior: Clip.hardEdge,
            width: 54.w,
            height: 76.h,
            radius: 18.w,
            child: visualEffectWidget(
              child: Center(
                child: Text(
                  "${logic.caveNum}个cave",
                  style: TextStyle(color: kAppWhiteColor, fontSize: 10.sp),
                  textAlign: TextAlign.center,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 2,
                ),
              ),
            ),
          ),
          for (int i = 0; i < logic.randomAvatars.length; i++)
            UIImage(
              margin: EdgeInsets.only(
                  left: 33.w * 4 + 54.w + 12.w + 8 * i, bottom: 22.h),
              width: 18.w,
              height: 18.w,
              radius: 9.w,
              // assetImage: "img_bg_home",
              httpImage: '$getImageBaseUrl${logic.randomAvatars[i]}',
              fit: BoxFit.cover,
            ),
          UIContainer(
            margin: EdgeInsets.only(left: 33.w * 4 + 54.w + 12.w, top: 22.h),
            child: Text(
              '目前${logic.caveUserNum}人正在加入',
              style: TextStyle(color: kAppWhiteColor, fontSize: 13.sp),
              overflow: TextOverflow.ellipsis,
            ),
          )
        ],
      ),
    );
  }

  Widget coveListView() {
    return ListView.builder(
      itemBuilder: (context, index) {
        return UIColumn(
          margin: EdgeInsets.only(bottom: 13.w, left: 10.w, right: 10.w),
          clipBehavior: Clip.hardEdge,
          color: kAppBlackColor,
          radius: 25.w,
          children: [
            UIRow(
              children: [
                UIText(
                  height: 30.w,
                  width: 72.w,
                  bottomRightRadius: 23.w,
                  color: kAppColor("#FFE800"),
                  textColor: kAppBlackColor,
                  text: logic.personCaves[index]['className'],
                  fontSize: 14.sp,
                  alignment: Alignment.center,
                ),
                const Expanded(child: UIContainer()),
                UIImage(
                  margin: EdgeInsets.only(right: 10.w, top: 3.w),
                  padding: EdgeInsets.all(5.w),
                  width: 20.w,
                  height: 20.w,
                  assetImage: 'arrow_right.png',
                )
              ],
            ),
            coveGridView(logic.personCaves[index]['caves'])
          ],
        );
      },
      itemCount: logic.personCaves.length,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
    );
  }

  Widget coveGridView(List<dynamic> caves) {
    return UIContainer(
      height: 84.w,
      margin: EdgeInsets.symmetric(vertical: 13.h),
      padding: EdgeInsets.only(left: 12.w),
      alignment: Alignment.centerLeft,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 1,
          mainAxisSpacing: 6.w,
          mainAxisExtent: 68.w,
        ),
        itemBuilder: (context, index) {
          return UIImage(
            width: 68.w,
            height: 84.w,
            radius: 12.w,
            fit: BoxFit.cover,
            // assetImage: "img_bg_home",
            disabledHttpBigImage: true,
            httpImage: !caves[index]['caveImg'].toString().startsWith('http')
                ? '$getImageBaseUrl${caves[index]['caveImg']}'
                : caves[index]['caveImg'],
            onTap: () {
              // logic.toDetailPage();
              if (caves[index]['join'] == true) {
                logic.toDetailPage(caves[index]['id']);
              } else {
                logic.toJoinPage(caves[index]['id']);
              }
            },
          );
        },
        itemCount: caves.length,
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}
